package cn.big.bigd.biocode.convert;

import cn.big.bigd.biocode.model.Publication;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.persistence.AttributeConverter;
import java.io.IOException;
import java.util.List;

/**
 *@Author wangfan
 *@Date 2017/12/4 14:47
 */

public class JpaConverterJson implements AttributeConverter<List<Publication>, String> {
private static final Logger logger = LoggerFactory.getLogger(JpaConverterJson.class);

  private final static ObjectMapper objectMapper = new ObjectMapper();

  @Override
  public String convertToDatabaseColumn(List<Publication> meta) {
    try {
      return objectMapper.writeValueAsString(meta);
    } catch (JsonProcessingException ex) {
      return null;
    }
  }

  @Override
  public List<Publication> convertToEntityAttribute(String dbData) {
    try {
      return objectMapper.readValue(dbData, new TypeReference<List<Publication>>(){});
    } catch (IOException ex) {
       logger.error("Unexpected IOEx decoding json from database: " + dbData);
      return null;
    }
  }

}